/*
 * Copyright (C) 2023 panpf <panpfpanpf@outlook.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.panpf.sketch.sample.ui.components.zoomimage.core

import com.github.panpf.sketch.Sketch
import com.github.panpf.sketch.asSketchImage
import com.github.panpf.zoomimage.subsampling.CacheTileBitmap
import com.github.panpf.zoomimage.subsampling.DesktopTileBitmap
import com.github.panpf.zoomimage.subsampling.TileBitmap
import com.github.panpf.zoomimage.subsampling.TileBitmapCache

class BufferedImageCacheTileBitmapCache constructor(
    private val sketch: Sketch,
) : TileBitmapCache {

    override fun get(key: String): CacheTileBitmap? {
        val bufferedImage = (sketch.memoryCache[key] as? BufferedImageValue)
            ?.image?.bitmap ?: return null
        return BufferedImageCacheTileBitmap(key, bufferedImage)
    }

    override fun put(
        key: String,
        tileBitmap: TileBitmap,
        imageUrl: String,
        imageInfo: com.github.panpf.zoomimage.subsampling.ImageInfo,
        disallowReuseBitmap: Boolean
    ): CacheTileBitmap? {
        val bufferedImage = (tileBitmap as? DesktopTileBitmap)?.bufferedImage ?: return null
        val newCacheValue = BufferedImageValue(bufferedImage.asSketchImage())
        if (sketch.memoryCache.put(key, newCacheValue) != 0) {
            return null
        }
        return BufferedImageCacheTileBitmap(key, bufferedImage)
    }
}